package org.rainwalk.library.api.log;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.rainwalk.library.util.RequestUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.StringJoiner;

/**
 * 日志打印代理
 *
 * @author 趁雨行 2021/7/6
 */
@Slf4j
@Aspect
@Component
@Order(999)
public class LogDelegate {

    @Around(value = "@annotation(ApiLog)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String ip = RequestUtil.getRemoteAddr(request);
        log.info("请求ip：{}", ip);

        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        ApiLog apiLog = method.getAnnotation(ApiLog.class);
        String value = apiLog.value();
        log.info("接口描述： {}", value);

        boolean isLogParam = apiLog.logParam();
        if (isLogParam) {
            Object[] args = pjp.getArgs();
            String[] argNames = signature.getParameterNames();
            StringJoiner joiner = new StringJoiner(", ");
            for (int i = 0; i < argNames.length; i++) {
                joiner.add(String.format("%s = %s", argNames[i], args[i].toString()));
            }
            log.info("接口入参：{}", joiner.toString());
        }

        Object obj = pjp.proceed();
        log.info("接口响应 ：{}", JSONUtil.toJsonStr(obj));
        return obj;
    }


}
